<template>
  <div id="app">
    <div class="tit">
      <span class="iconfont icon-fanhui" @click="back"></span>
      <p class="h1">{{addressId?'编辑':'新增'}}收货地址</p>
    </div>
    <div class="msg">
      <mt-field label="用户名" placeholder="您的姓名" :state="nameStatus" v-model="username" @blur.native.capture="changeName"></mt-field>
      <mt-field label="手机号" placeholder="您的手机号" type="tel" :state="phoneStatus" v-model="phone" @blur.native.capture="change"></mt-field>
      <div class="Area">
        <div class="control">
          <p>收货地址</p>
          <input type="text" placeholder="省/市/区" v-model="region" maxlength="80" readonly="readonly" @click="showAddressPicker" />
        </div>
        <!-- 省市区地址选择 -->
        <mt-popup v-model="regionVisible" position="bottom">
          <mt-button type="default" @click="show">取消</mt-button>
          <mt-button type="primary" @click="show">确定</mt-button>
          <mt-picker :slots="myAddressSlots" valueKey="name" :visibleItemCount="5" @change="addressChange" :itemHeight="40"></mt-picker>
        </mt-popup>
        <p>详细地址</p>
        <input type="text" placeholder="（如门牌号等）" v-model="detailed">
      </div>
    </div>
    <a class="add" :href="href" @click="fix">确定</a>
  </div>
</template>
<script>
    import addrlist from '@/assets/address/threeLevelAddress.json'
    export default {
        name:'App',
        components:{

        },
        data(){
            return{
                value:[],
                def:[' 默认地址'],
                username:'',
                nameStatus:'',
                phone:'',
                phoneStatus:'',
                addressId:'',
                province:'',
                city:'',
                country:'',
                address:'',
                userId:'',
                detailed:'',
                regionVisible: false, // 弹出框默认是否可见
                region: '',
                // picker组件插槽
                myAddressSlots: [
                    // 省
                    {
                        flex: 1,
                        values: this.getProvinceArr(), // ['广东'], // 省份数组
                        className: 'slot1',
                        textAlign: 'left'
                    },
                    // 分隔符
                    {
                        divider: true,
                        content: '',
                        className: 'slot2'
                    },
                    // 市
                    {
                        flex: 1,
                        values: this.getCityArr("440000"), // []
                        className: 'slot3',
                        textAlign: 'left'
                    },
                    {
                        divider: true,
                        content: '',
                        className: 'slot4'
                    },
                    // 县
                    {
                        flex: 1,
                        values: this.getCountyArr("440500"), // []
                        className: 'slot5',
                        textAlign: 'left'
                    }
                ],
                href:'javascript:;'
            }
        },
        mounted(){
            //修改地址获取对应地址id
            let str=location. href;
            this.url2json(str);
            this.axios({
                method: 'get',
                url: '/api/addressOperation/updateAddress',
                params: {
                    "userId":"3"
                }
            }).then((res)=>{
                res.data.data.map(v=>{
                    if (v.addressId==this.addressId) {
                        this.address=v.province+''+v.city+''+v.country;
                        this.username=v.receiveName;
                        this.phone=v.receiveTel;
                        this.province=v.province;
                        this.city=v.city;
                        this.country=v.country;
                        this.detailed=v.detailed;
                        this.region=v.province+'-'+v.city+'-'+v.country;
                        this.detailed=v.detailed;
                        this.userId=v.userId;
                        console.log(this.userId)
                    }
                })
            }).catch(()=>{
                console.log('网络错误')
            })
            console.log(this.address)
            // this.axios({
            //     method:'post',
            //     url:'http://115.28.137.176:7071/addressOperation/selectAddress',
            //     headers:{
            //       "token":"1111"
            //     },
            //     data:{
            //         "userId":"1"
            //     }
            // }).then((res)=>{
            //     console.log(res);
            // }).catch(()=>{
            //     console.log('网络错误')
            // });
        },
        methods:{
            //修改地址获取对应地址id
            url2json(str){
                var reg = /[^?]*\??([^&]+)=([^&]+)/g, result, obj = {};
                while(result = reg.exec(str)) {
                    obj[result[1]] = result[2];
                }
                this.addressId=obj.addressId
            },
            //名字正则
            changeName(){
              let reg=/[\u4e00-\u9fa5]/;
                if (!reg.test(this.username)||this.username=='') {
                    this.nameStatus="error";
                }else {
                    this.nameStatus="success";
                }
            },
            //手机正则
            change(){
                let reg=/^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/;
                if (!reg.test(this.phone)||this.phone=='') {
                    this.phoneStatus="error";
                }else {
                    this.phoneStatus="success";
                }
            },
            //返回上一页
            back(){
                this.$router.go(-1)
            },
            //点击地址弹框隐藏
            show(){
                this.regionVisible = false;
            },
            //点击地址弹框显示
            showAddressPicker () {
                this.regionVisible = true;
            },
            //地址改变
            addressChange (picker, values) {
                this.province = values[0]['name'] ? values[0]['name'] : '';
                this.city = values[1]['name'] ? values[1]['name'] : '';
                this.country = values[2]['name'] ? values[2]['name'] : '';
                this.region = this.province + '-' + this.city + '-' + this.country;

                // 给市、县赋值
                picker.setSlotValues(1, this.getCityArr(values[0]["code"]));
                picker.setSlotValues(2, this.getCountyArr(values[1]["code"]));
            },
            getProvinceArr () {
                let gp = addrlist.province;
                return gp;
            },
            //遍历出省
            getCityArr (code) {
                let p = addrlist.city[code];
                let cityname = p.map(item => item.name);
                // console.log(p);
                return p;
            },
            //遍历市
            getCountyArr (code) {
                let s = addrlist.area[code];
                if (s) {
                    let countyname = s.map(item => item.name);
                }
                // console.table(code, s);
                return s;
            },
            //点击完成判断正则
            fix(){
                if (this.nameStatus=='success'||this.phoneStatus=='success') {
                    console.log(this.region+''+this.detailed)
                    this.axios({
                        method:'post',
                        url:'/api/addressOperation/addAddress',
                        headers:{
                          "token":"1111"
                        },
                        data:JSON.stringify({
                            "addressId":this.addressId,
                            "receiveName":this.username,
                            "receiveTel":this.phone,
                            "province":this.province,
                            "city":this.city,
                            "country":this.country,
                            "detailed":this.detailed,
                            "userId":this.userId,
                        })
                    }).then((res)=>{
                        this.href='./address.html';
                    }).catch(()=>{
                        console.log('网络错误')
                    });
                }
            }
        }

    }
</script>
<style lang="less">
  @baseFontSize:20px;
  @baseSize:20;
  html{
    font-size: @baseFontSize;
  }
  .px2rem(@name,@px){
      @{name}:@px / 2 / @baseSize * 1rem;
  }

  *{
    margin: 0;
    padding: 0;
    text-decoration: none;
    list-style: none;
  }
#app {
  .tit{
    position: relative;
    background: orange;
    span{
      position: absolute;
      left: 15px;
      top: 10px;
    }
    .h1{
      text-align: center;
      .px2rem(line-height,80);
      .px2rem(height,80);
      border-bottom: 1px solid gray;
      color: white;
    }
  }
  .Area{
    p{
      .px2rem(margin-top,20);
      .px2rem(font-size,30);
      .px2rem(padding-left,20);
    }
    input{
      .px2rem(width,750);
      .px2rem(height,80);
      border: none;
      outline: none;
      border-bottom: 1px solid gray;
      .px2rem(padding-left,40);
      .px2rem(margin-top,20);
    }
    .mint-button--default{
      .px2rem(margin-top,20);
      .px2rem(margin-left,20);
    }
    .mint-button--primary{
      .px2rem(margin-top,20);
      float: right;
      .px2rem(margin-right,20);
    }
  }
  .add{
    position: absolute;
    left: 0;
    bottom: 0;
    .px2rem(width,750);
    .px2rem(height,80);
    background: orangered;
    color: white;
    outline: none;
    border: none;
    text-align: center;
    .px2rem(font-size,30);
    .px2rem(line-height,80);
  }
}


</style>
